# data1_analysis.py
import numpy as np
import math
import os

# 创建静态文件夹（如果不存在）
STATIC_DIR = 'static/images'
os.makedirs(STATIC_DIR, exist_ok=True)

def tem_curve(data):
    """温度曲线数据生成"""
    try:
        hour = []
        tem = []
        
        for row in data:
            try:
                h = int(row[0]) if row[0] else 0
                t = float(row[1]) if row[1] and row[1] != '' else 0
                
                if not math.isnan(t):
                    hour.append(h)
                    tem.append(t)
            except (ValueError, TypeError, IndexError):
                # 跳过无效数据
                continue
        
        # 确保数据不为空
        if not hour or not tem:
            # 返回默认数据
            return {
                'xAxis': list(range(24)),
                'series': [{'name': '温度', 'type': 'line', 'data': [0] * 24}],
                'min': 0,
                'max': 1,
                'avg': 0
            }
        
        # 继续原有逻辑，但确保数据完整性
        for i in range(0, 24):
            if i not in hour:
                # 如果该小时数据不存在，使用前一小时数据或默认值
                if i > 0 and i-1 in hour:
                    tem_value = tem[hour.index(i-1)]
                else:
                    tem_value = 0  # 默认值
                # 插入到相应位置
                hour.append(i)
                tem.append(tem_value)
                # 重新按小时排序
                hour_tem = sorted(zip(hour, tem))
                hour, tem = zip(*hour_tem)
        
        # 确保有24小时的数据
        if len(hour) < 24:
            for i in range(24):
                if i not in hour:
                    hour = list(hour)
                    tem = list(tem)
                    hour.append(i)
                    tem.append(0)  # 默认值
                    # 重新按小时排序
                    hour_tem = sorted(zip(hour, tem))
                    hour, tem = zip(*hour_tem)
        
        tem_ave = sum(tem) / 24  # 求平均温度
        tem_max = max(tem)
        tem_max_hour = hour[tem.index(tem_max)]  # 求最高温度
        tem_min = min(tem)
        tem_min_hour = hour[tem.index(tem_min)]  # 求最低温度
        
        # 生成X轴数据点
        x = list(range(24))
        y = []
        for i in range(0, 24):
            y.append(tem[hour.index(i)] if i in hour else 0)
        
        # 返回ECharts所需的数据
        return {
            'xAxis': x,
            'series': [
                {
                    'name': '温度',
                    'type': 'line',
                    'data': y,
                    'markPoint': {
                        'data': [
                            {'value': tem_max, 'xAxis': tem_max_hour, 'yAxis': tem_max, 'name': '最高温度'},
                            {'value': tem_min, 'xAxis': tem_min_hour, 'yAxis': tem_min, 'name': '最低温度'}
                        ]
                    },
                    'markLine': {
                        'data': [
                            {'type': 'average', 'name': '平均温度'}
                        ]
                    }
                }
            ],
            'min': tem_min - 1,
            'max': tem_max + 1,
            'avg': tem_ave
        }
    except Exception as e:
        # 发生任何错误时返回默认数据
        print(f"温度曲线数据生成错误: {str(e)}")
        return {
            'xAxis': list(range(24)),
            'series': [{'name': '温度', 'type': 'line', 'data': [0] * 24}],
            'min': 0,
            'max': 1,
            'avg': 0
        }


def hum_curve(data):
    """相对湿度曲线数据生成"""
    try:
        hour = []
        hum = []
        
        for row in data:
            try:
                if len(row) > 5:  # 确保行有足够的列
                    h = int(row[0]) if row[0] else 0
                    h_value = float(row[5]) if row[5] and row[5] != '' else 0
                    
                    if not math.isnan(h_value):
                        hour.append(h)
                        hum.append(h_value)
            except (ValueError, TypeError, IndexError):
                # 跳过无效数据
                continue
        
        # 确保数据不为空
        if not hour or not hum:
            # 返回默认数据
            return {
                'xAxis': list(range(24)),
                'series': [{'name': '相对湿度', 'type': 'line', 'data': [0] * 24}],
                'min': 0,
                'max': 100,
                'avg': 50
            }
            
        # 继续原有逻辑，但确保数据完整性
        for i in range(0, 24):
            if i not in hour:
                # 如果该小时数据不存在，使用前一小时数据或默认值
                if i > 0 and i-1 in hour:
                    hum_value = hum[hour.index(i-1)]
                else:
                    hum_value = 0  # 默认值
                # 插入到相应位置
                hour.append(i)
                hum.append(hum_value)
                # 重新按小时排序
                hour_hum = sorted(zip(hour, hum))
                hour, hum = zip(*hour_hum)
        
        # 确保有24小时的数据
        if len(hour) < 24:
            for i in range(24):
                if i not in hour:
                    hour = list(hour)
                    hum = list(hum)
                    hour.append(i)
                    hum.append(0)  # 默认值
                    # 重新按小时排序
                    hour_hum = sorted(zip(hour, hum))
                    hour, hum = zip(*hour_hum)
        
        hum_ave = sum(hum) / 24  # 求平均相对湿度
        hum_max = max(hum)
        hum_max_hour = hour[hum.index(hum_max)]  # 求最高相对湿度
        hum_min = min(hum)
        hum_min_hour = hour[hum.index(hum_min)]  # 求最低相对湿度
        
        # 生成X轴数据点
        x = list(range(24))
        y = []
        for i in range(0, 24):
            y.append(hum[hour.index(i)] if i in hour else 0)
        
        # 返回ECharts所需的数据
        return {
            'xAxis': x,
            'series': [
                {
                    'name': '相对湿度',
                    'type': 'line',
                    'data': y,
                    'markPoint': {
                        'data': [
                            {'value': hum_max, 'xAxis': hum_max_hour, 'yAxis': hum_max, 'name': '最高湿度'},
                            {'value': hum_min, 'xAxis': hum_min_hour, 'yAxis': hum_min, 'name': '最低湿度'}
                        ]
                    },
                    'markLine': {
                        'data': [
                            {'type': 'average', 'name': '平均湿度'}
                        ]
                    }
                }
            ],
            'min': hum_min - 1,
            'max': hum_max + 1,
            'avg': hum_ave
        }
    except Exception as e:
        # 发生任何错误时返回默认数据
        print(f"湿度曲线数据生成错误: {str(e)}")
        return {
            'xAxis': list(range(24)),
            'series': [{'name': '相对湿度', 'type': 'line', 'data': [0] * 24}],
            'min': 0,
            'max': 100,
            'avg': 50
        }


def air_curve(data):
    """空气质量曲线数据生成"""
    try:
        hour = []
        air = []
        
        for row in data:
            try:
                if len(row) > 6:  # 确保行有足够的列
                    h = int(row[0]) if row[0] else 0
                    a_value = float(row[6]) if row[6] and row[6] != '' else 0
                    
                    if not math.isnan(a_value):
                        hour.append(h)
                        air.append(a_value)
            except (ValueError, TypeError, IndexError):
                # 跳过无效数据
                continue
        
        # 确保数据不为空
        if not hour or not air:
            # 返回默认数据
            default_data = [50] * 24  # 默认良好空气质量
            default_colors = ['#90EE90'] * 24  # 绿色，表示良好
            return {
                'xAxis': list(range(24)),
                'series': [{'name': '空气质量', 'type': 'bar', 'data': default_data}],
                'colors': default_colors,
                'min': 0,
                'max': 100,
                'avg': 50
            }
        
        # 继续原有逻辑，但确保数据完整性
        for i in range(0, 24):
            if i not in hour:
                # 如果该小时数据不存在，使用前一小时数据或默认值
                if i > 0 and i-1 in hour:
                    air_value = air[hour.index(i-1)]
                else:
                    air_value = 0  # 默认值
                # 插入到相应位置
                hour.append(i)
                air.append(air_value)
                # 重新按小时排序
                hour_air = sorted(zip(hour, air))
                hour, air = zip(*hour_air)
        
        # 确保有24小时的数据
        if len(hour) < 24:
            for i in range(24):
                if i not in hour:
                    hour = list(hour)
                    air = list(air)
                    hour.append(i)
                    air.append(0)  # 默认值
                    # 重新按小时排序
                    hour_air = sorted(zip(hour, air))
                    hour, air = zip(*hour_air)
        
        air_ave = sum(air) / 24  # 求平均空气质量
        air_max = max(air)
        air_max_hour = hour[air.index(air_max)]  # 求最高空气质量
        air_min = min(air)
        air_min_hour = hour[air.index(air_min)]  # 求最低空气质量
        
        # 生成数据点
        x = list(range(24))
        y = []
        colors = []
        for i in range(0, 24):
            y_value = air[hour.index(i)] if i in hour else 0
            y.append(y_value)
            
            # 根据空气质量等级定义颜色
            if y_value <= 50:
                colors.append('#90EE90')  # 1等级 - lightgreen
            elif y_value <= 100:
                colors.append('#F5DEB3')  # 2等级 - wheat
            elif y_value <= 150:
                colors.append('#FFA500')  # 3等级 - orange
            elif y_value <= 200:
                colors.append('#FF4500')  # 4等级 - orangered
            elif y_value <= 300:
                colors.append('#9400D3')  # 5等级 - darkviolet
            else:
                colors.append('#800000')  # 6等级 - maroon
        
        # 返回ECharts所需的数据
        return {
            'xAxis': x,
            'series': [
                {
                    'name': '空气质量',
                    'type': 'bar',
                    'data': y,
                    'itemStyle': {
                        'colorArray': colors  # 改为颜色数组，前端使用
                    },
                    'markPoint': {
                        'data': [
                            {'value': air_max, 'xAxis': air_max_hour, 'yAxis': air_max, 'name': '最高值'},
                            {'value': air_min, 'xAxis': air_min_hour, 'yAxis': air_min, 'name': '最低值'}
                        ]
                    },
                    'markLine': {
                        'data': [
                            {'type': 'average', 'name': '平均值'}
                        ]
                    }
                }
            ],
            'colors': colors,
            'min': 0,
            'max': air_max + 10,
            'avg': air_ave
        }
    except Exception as e:
        # 发生任何错误时返回默认数据
        print(f"空气质量曲线数据生成错误: {str(e)}")
        default_data = [50] * 24  # 默认良好空气质量
        default_colors = ['#90EE90'] * 24  # 绿色，表示良好
        return {
            'xAxis': list(range(24)),
            'series': [{'name': '空气质量', 'type': 'bar', 'data': default_data}],
            'colors': default_colors,
            'min': 0,
            'max': 100,
            'avg': 50
        }


def wind_radar(data):
    """风向雷达图数据生成"""
    hour = [int(row[0]) for row in data]
    wind = [row[2] for row in data]  # 风力方向是第3列
    wind_speed = [float(row[3]) for row in data]  # 风级是第4列
    wind_dirs = ["东北风", "东风", "东南风", "南风", "西南风", "西风", "西北风", "北风"]
    wind_angles = [45, 360, 315, 270, 225, 180, 135, 90]
    
    # 将文本风向转为角度
    wind_data = []
    for i in range(min(len(wind), 24)):
        wind_direction = wind[i]
        if wind_direction == "北风":
            wind_data.append(90)
        elif wind_direction == "南风":
            wind_data.append(270)
        elif wind_direction == "西风":
            wind_data.append(180)
        elif wind_direction == "东风":
            wind_data.append(360)
        elif wind_direction == "东北风":
            wind_data.append(45)
        elif wind_direction == "西北风":
            wind_data.append(135)
        elif wind_direction == "西南风":
            wind_data.append(225)
        elif wind_direction == "东南风":
            wind_data.append(315)
    
    # 统计每个方向的风速
    degs = np.arange(45, 361, 45)
    wind_speed_by_dir = [0] * 8
    wind_count_by_dir = [0] * 8
    
    for i in range(len(wind_data)):
        wind_deg = wind_data[i]
        speed = wind_speed[i] if i < len(wind_speed) else 0
        
        for j in range(len(degs)):
            if wind_deg == degs[j]:
                wind_speed_by_dir[j] += speed
                wind_count_by_dir[j] += 1
                break
    
    # 计算每个方向的平均风速
    for i in range(len(wind_speed_by_dir)):
        if wind_count_by_dir[i] > 0:
            wind_speed_by_dir[i] /= wind_count_by_dir[i]
    
    # 返回雷达图所需数据
    return {
        'indicator': [{'name': wind_dirs[i], 'max': max(wind_speed_by_dir) + 2} for i in range(8)],
        'data': wind_speed_by_dir
    }


def calc_corr(a, b):
    """计算相关系数"""
    a_mean = sum(a) / len(a)
    b_mean = sum(b) / len(b)
    
    numerator = sum((a[i] - a_mean) * (b[i] - b_mean) for i in range(len(a)))
    denominator = (sum((a[i] - a_mean) ** 2 for i in range(len(a))) * sum((b[i] - b_mean) ** 2 for i in range(len(b)))) ** 0.5
    
    if denominator == 0:
        return 0
    return numerator / denominator


def corr_tem_hum(data):
    """温湿度相关性分析"""
    hour = [int(row[0]) for row in data]
    tem = [float(row[1]) for row in data]  # 温度是第2列
    hum = [float(row[5]) for row in data]  # 相对湿度是第6列
    
    # 确保数据完整
    x = []
    y_tem = []
    y_hum = []
    for i in range(0, 24):
        if i in hour:
            x.append(i)
            y_tem.append(tem[hour.index(i)])
            y_hum.append(hum[hour.index(i)])
    
    # 计算相关系数
    corr_value = calc_corr(y_tem, y_hum)
    
    # 返回散点图所需数据
    return {
        'x': x,
        'tem': y_tem,
        'hum': y_hum,
        'corr_value': corr_value
    }


def analyze_weather1(weather_data=None):
    """24小时天气数据分析"""
    try:
        # 如果直接提供了数据，则使用提供的数据
        if weather_data is not None:
            data = weather_data
        else:
            # 默认提示信息，实际上由于重构，这个分支不应该被执行
            return {"error": "未提供天气数据"}
            
        # 分析数据
        tem_data = tem_curve(data)
        hum_data = hum_curve(data)
        air_data = air_curve(data)
        wind_data = wind_radar(data)
        corr_data = corr_tem_hum(data)
        
        # 合并结果
        result = {
            'tem': tem_data,
            'hum': hum_data,
            'air': air_data,
            'wind': wind_data,
            'corr': corr_data,
            'corr_value': corr_data['corr_value']
        }
        
        return result
        
    except Exception as e:
        import traceback
        return {
            "error": f"分析数据时出错: {str(e)}",
            "traceback": traceback.format_exc()
        }


if __name__ == '__main__':
    analyze_weather1()
